package com.sf.asp.config.shiro;

import com.sf.asp.entity.User;
import com.sf.asp.service.UserService;
import org.apache.catalina.security.SecurityUtil;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationException;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * 身份验证核心
 */
@Service
public class MyShiroRealm extends AuthorizingRealm {

    @Autowired
    private UserService userService;

    /**
     * 授权回调函数，进行鉴权，但是缓存中无用户的授权信息
     * @param principalCollection 授权认证
     * @return 授权信息
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        if (principalCollection == null){
            throw new AuthorizationException("principals should not be null");
        }

        SimpleAuthenticationInfo authenticationInfo = new SimpleAuthenticationInfo();
        User user = (User) principalCollection.getPrimaryPrincipal();

      /*  List<TsysRole> tsysRoles= roleDao.queryUserRole(uid);
        for(TsysRole userrole:tsysRoles){
            //System.out.println("角色名字:"+gson.toJson(userrole));
            String rolid=userrole.getId();//角色id
            authorizationInfo.addRole(userrole.getName());//添加角色名字
            List<TsysPermission> permissions=permissionDao.queryRoleId(rolid);
            for(TsysPermission p:permissions){
                //System.out.println("角色下面的权限:"+gson.toJson(p));
                if(StringUtils.isNotEmpty(p.getPerms())){
                    authorizationInfo.addStringPermission(p.getPerms());
                }

            }*/


        return null;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        if (token.getPrincipal() == null){
            return null;
        }

        String username = (String) token.getPrincipal();
        String password = new String((char[]) token.getCredentials());
        User user = userService.getUserByUsername(username);
        if (user != null){
            return new SimpleAuthenticationInfo(user,user.getPassword(),getName());
        }
        return null;
    }


    /**
     * 清除缓存权限
     */
    public void clearCachedAuthorizationInfo(){
        this.clearCachedAuthorizationInfo(SecurityUtils.getSubject().getPrincipals());
    }
}
